package com.tourism.service.impl;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.tourism.core.common.exception.CustomException;
import com.tourism.core.common.utils.ResultCodeEnum;
import com.tourism.core.storage.service.StorageService;
import com.tourism.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件服务实现类
 *
 * @author lucky
 */
@Service
public class FileServiceImpl
        implements FileService {

    @Autowired
    private StorageService storageService;

    @Override
    public String upload(MultipartFile multipartFile) {
        try {
            // 获取文件名
            String filename = multipartFile.getOriginalFilename();

            long size = multipartFile.getSize();

            // 判断文件大小
            if (size > 1024 * 1024 * 10) {
                throw new CustomException(ResultCodeEnum.FILE_TOO_LARGE);
            }

            // 获取文件名
            String md5 = RandomUtil.randomString(12);
            String generateFilename = generateFilename(multipartFile.getOriginalFilename(), md5);

            // 上传文件
            return storageService.upload(multipartFile.getBytes(), generateFilename, multipartFile.getContentType());
        } catch (Exception e) {
            throw new CustomException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }
    }

    @Override
    public void download(String fileName) {

    }


    /**
     * 传入文件名返回新的文件名
     *
     * @param fileName 文件名
     * @return 新的文件名
     */
    public static String generateFilename(String fileName, String md5) {
        if (fileName == null) {
            throw new CustomException(ResultCodeEnum.FILE_NOT_FIND);
        }

        // 获取加密的文件名
        String md5FileName = DigestUtil.md5Hex(fileName + md5);

        // 获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));

        // 返回新的文件名
        return md5FileName + suffix;
    }
}
